<?php


namespace app\api\controller\v1;


use app\api\controller\v1\Clue as ClueModel;
use app\common\model\ClueErrorLog;
use app\lib\exception\ParamException;
use fast\Http;
use other\Rsa;
use think\Db;

/**
 * 企惠通杭州如盈
 * 【生产环境】
 *
 * 渠道：202306412
 * key:   UUl293Si51M8FGcU
 * 撞库：https://yykapi.uekery.cn/uranus-api/api/flow/common/v2/preApply
 * 申请：https://yykapi.uekery.cn/uranus-api/api/flow/common/v2/apply
 *
 * 资质：哈密市，有房
 */
class QiHuiTongHangZhouRuYing
{

//    private $url='http://apitest.qihuiry.cn';
//
//    private $channelCode='122331';
//    private $key='8DHcDu1LL7m5o55R';

    private $url='https://yykapi.uekery.cn';

    private $channelCode='202306412';
    private $key='UUl293Si51M8FGcU';

    public function pushClue($mapping, $clue_info, $listPush)
    {

        $apiName = '【' . $mapping['api_name'] . '】';

//        $clue_info['clue_name']='张测试';
//        $clue_info['phone']='15988888888';
//        $clue_info['ip']='192.168.1.1';


        $clue_rule = json_decode($mapping['rule_json'], true);
        $params = [];
        if (!$clue_rule) {
            $errMsg = $apiName . '读取商户接收规则失败';
            ClueErrorLog::record($clue_info['clue_id'], $errMsg, $clue_info);
            model('Clue')->where('id', $clue_info['id'])->update(['err_msg' => $errMsg]);
            throw new ParamException(['msg'=>$errMsg,'errorCode'=>10001]);
        } else {

            foreach ($clue_rule as $v){
                $params[$v['curr']] = $clue_info[$v['orig']];
                if($v['orig'] == 'city'){
                    if (!empty($clue_info['show_city'])) {
                        if (strpos($clue_info['show_city'], '-') !== false) {
                            $city_t = explode('-', $clue_info['show_city']);
                            if (count($city_t) == 3) {
                                $showCity =$city_t[0].'-'.$city_t[1];
                            } elseif (count($city_t) == 2) {
                                $showCity =$city_t[0].'-'.$city_t[1];
                            } elseif (count($city_t) == 1) {
                                $showCity = $city_t[0];
                            }
                        }else{
                            $showCity=$clue_info['show_city'];
                        }
                        $params[$v['curr']]=add_city_mark($showCity);
                    }else{
                        $citys = explode('-',$clue_info[$v['orig']]);
                        $city_info = Db::name('city')->where(['type'=>2,'id'=>$citys[1]])->find();
                        $params[$v['curr']] = add_city_mark($city_info['name']);
                    }

                }
            }

            if(strpos($clue_info['apply_limit'], '-') !== false){
                $moneyArr=explode('-',$clue_info['apply_limit']);
                $moneyNum=count($moneyArr);
                if($moneyNum==1){
                    $MoneyStr=$moneyArr[0];
                }else{
                    $MoneyStr=$moneyArr[1];
                }
            }else{
                $MoneyStr=$clue_info['apply_limit'];
            }

            if(strpos($MoneyStr, '万') !== false){
                preg_match('/\d+/',$MoneyStr,$number);
                if(empty($number[0])){
                    $MoneyStr=0;
                }else{
                    $MoneyStr=$number[0];
                }
                $loanAmount=$MoneyStr*10000;
            }else{
                preg_match('/\d+/',$MoneyStr,$number);
                if(empty($number[0])){
                    $MoneyStr=0;
                }else{
                    $MoneyStr=$number[0];
                }
                $loanAmount=intval($MoneyStr);
            }

            if($loanAmount<50000){
                $params['loanAmount']=1;
            }elseif ($loanAmount>=50000 && $loanAmount<100000){
                $params['loanAmount']=2;
            }elseif ($loanAmount>=100000 && $loanAmount<200000){
                $params['loanAmount']=3;
            }elseif ($loanAmount>=200000){
                $params['loanAmount']=4;
            }


//            $params['loanTime']=3;//贷款时间2（6个月）3（12个月）4（24个月）5（36个月）默认 3
//            $params['profession']=1;//职业  1(上班族) 2（自由职业）3（私营企业主）4（公务员/国企）默认 1
//            $params['zhima']=3;//芝麻分 1（600-650）2（650-700）3（700以上）4（无）5（600以下）默认 4
//            $params['providentFund']=4;//公积金1（6个月以下）2（6-12个月）3（12个月以上）4（无）默认4
//            $params['overdue']=1;//逾期记录1（信用良好）2（当前逾期中）默认1
//            $params['socialSecurity']=4;//社保1（6个月以下）2（6-12个月）3（12个月以上）4（无）默认4
//            $params['commericalInsurance']=3;//保单0（6个月以下）1（6-12个月）2（12个月以上）3（无）默认3
//            $params['house']=2;//名下房产1（有房产）2（无房产）默认2
//            $params['vehicle']=2;//名下车1（有车）2（无车）默认2
//            $params['creditCard']=4;//信用卡额度 1 (1万元以下) 2 (1万-3万) 3 (3万以上) 4 (无信用卡) 默认4
//            $params['loanPurpose']=1;//贷款用途 1 (日常消费) 2 (装修) 3 (医疗) 4 (教育) 5 (其他) 默认1

            $params['loanTime']=3;//贷款时间2（6个月）3（12个月）4（24个月）5（36个月）默认 3
            $params['profession']=4;//职业  1(上班族) 2（自由职业）3（私营企业主）4（公务员/国企）默认 1
            $params['zhima']=3;//芝麻分 1（600-650）2（650-700）3（700以上）4（无）5（600以下）默认 4
            $params['providentFund']=3;//公积金1（6个月以下）2（6-12个月）3（12个月以上）4（无）默认4
            $params['overdue']=1;//逾期记录1（信用良好）2（当前逾期中）默认1
            $params['socialSecurity']=3;//社保1（6个月以下）2（6-12个月）3（12个月以上）4（无）默认4
            $params['commericalInsurance']=2;//保单0（6个月以下）1（6-12个月）2（12个月以上）3（无）默认3
            $params['house']=1;//名下房产1（有房产）2（无房产）默认2
            $params['vehicle']=1;//名下车1（有车）2（无车）默认2
            $params['creditCard']=4;//信用卡额度 1 (1万元以下) 2 (1万-3万) 3 (3万以上) 4 (无信用卡) 默认4
            $params['loanPurpose']=1;//贷款用途 1 (日常消费) 2 (装修) 3 (医疗) 4 (教育) 5 (其他) 默认1

            $params['agreeProtocol']='https://file.uekery.cn/agreement/index.html#/';//用户授权协议（ 个人信息授权书_合作方与用户）


            $remarkStr='';
            //渠道
            if(!empty($clue_info['push_channel'])){
                $source=$clue_info['push_channel'];
            }else{
                $advInfo=Db::name('account')->where('adv_id',$clue_info['adv_id'])->find();
                $source=$advInfo['show_channel'];
                if(empty($source)){
                    $source=get_channel_desc($clue_info['type']);

                }
            }
            $remarkStr.=$source.'-';


            if($clue_info['pro_id']==3){
                $params['house']=1;
                $remarkStr.='有房-';
            }elseif ($clue_info['pro_id']==4){
                $params['vehicle']=1;
                $remarkStr.='有车-';
            }elseif ($clue_info['pro_id']==6){
                $params['providentFund']=3;
                $remarkStr.='有公积金-';
            }elseif ($clue_info['pro_id']==7){
                $params['profession']=3;
            }elseif ($clue_info['pro_id']==5){
                if(strpos($clue_info['remark'], '车') !== false){
                    $params['vehicle']=1;
                }elseif (strpos($clue_info['remark'], '房') !== false){
                    $params['house']=1;
                }elseif (strpos($clue_info['remark'], '公积金') !== false){
                    $params['providentFund']=3;
                }
            }else{
                $errMsg=$apiName.'线索推送商户处理失败贷款类型不符';
                ClueErrorLog::record($clue_info['clue_id'],$errMsg,$params);
                model('Clue')->where('id',$clue_info['id'])->update(['err_msg'=>$errMsg]);
                throw new ParamException(['msg'=>$errMsg,'errorCode'=>10001]);
            }

            if(empty($clue_info['remark'])){
            }else{
                $remark=json_decode($clue_info['remark'],true);
                if (is_array($remark)){
                    $remarkArr=[];
                    $keys=array_keys($remark);
                    $b=false;//默认索引
                    //判断关联数组还是索引数组
                    foreach($keys as $value){
                        if(!is_int($value)){
                            $b=true;
                            break;
                        }
                    }
                    //是关联数组
                    if($b){
                        foreach ($remark as $kk=>$vv){
                            if(strpos($kk, '城市') !== false){
                            }else{
                                $remarkArr[]=$vv;
                            }
                        }
                    }else{
                        foreach ($remark as $vv){
                            if($clue_info['type']==1){
                                if(strpos($vv['name'], '城市') !== false){
                                }else{
                                    $remarkArr[]=$vv['value'];
                                }
                            }else{
                                if(isset($vv['name'])&&isset($vv['value'])){
                                    if(strpos($vv['name'], '城市') !== false){
                                    }else{
                                        $remarkArr[]=$vv['value'];
                                    }
                                }else{
                                    $remarkArr[]=json_encode($vv,JSON_UNESCAPED_UNICODE);
                                }
                            }
                        }
                    }
                }else{
                    $remarkArr[]=$remark;
                }
                $remarkStr=$remarkStr.implode('|',$remarkArr);
            }

//            $params['house']=1;
//            $params['city']='哈密市';
            if($params['age']==0){
                $params['age']=mt_rand(30,50);
            }

            $this->getValidate($apiName,$clue_info,$params); // 手机号码的撞库

//            dump($params);

            $keyData=$this->encrypt(json_encode($params,JSON_UNESCAPED_UNICODE));
            $postParams=[
                'timestamp'=>time().'000',
                'reqId'=>create_order(),
                'data'=>$keyData,
                'channelCode'=>$this->channelCode
            ];

            $postData['param']=$params;
            $postData['post_param']=$postParams;
//            dump($postData);
            $api_url = $mapping['api_url'];


            $res_json = $this->postJson($api_url, $postParams);
//           dump($res_json);
            $res = json_decode($res_json, true);
//            dump($res);die;
            if (!empty($res)) {
                $res['params'] = $postData;
                if ($res['code'] != 0) {
                    $errMsg = $apiName . '线索推送商户处理失败：' . $res['msg'];
                    ClueErrorLog::record($clue_info['clue_id'], $errMsg, $res);
                    model('Clue')->where('id', $clue_info['id'])->update(['err_msg' => $errMsg]);
                    throw new ParamException(['msg' => $errMsg, 'errorCode' => 10001]);
                }
            } else {
                $errMsg = $apiName . '线索推送商户请求失败';
                ClueErrorLog::record($clue_info['clue_id'], $errMsg, $postData);
                model('Clue')->where('id', $clue_info['id'])->update(['err_msg' => $errMsg]);
                throw new ParamException(['msg' => $errMsg, 'errorCode' => 10001]);
            }
            return $res;
        }
    }

    private function getSign($data){
        $data['appkey']=$this->appKey;

//        dump($data);
        ksort($data);

//        dump($data);

        // 生成url的形式
//    $str = http_build_query($data, null, '&', PHP_QUERY_RFC3986);

        $str = '';
        foreach ($data as $key => $value) {
            $str .= $key . '=' . $value . '&';
        }
        $str = trim($str, '&');
        // 生成sign
//        $signStr = $str . '&key=' . $token;
//    dump($str);
        return sha1($str);
    }

    function encrypt($input){
//        return base64_encode(openssl_encrypt($input, 'AES-128-CBC', $this->aeskey, OPENSSL_RAW_DATA,$this->aesiv));

        $str = openssl_encrypt($input, 'AES-128-ECB' , $this->key,OPENSSL_RAW_DATA);
        $data = base64_encode($str);
        return  $data;
    }

//可以直接用
    public function getValidate($apiName,$clue_info,$params)
    {
        $api_url = $this->url.'/uranus-api/api/flow/common/v2/preApply';


        $phoneMd5=strtolower(md5($params['phone']));
        $params['phoneMd5']=$phoneMd5;
        unset($params['phone']);
        unset($params['agreeProtocol']);

        $res=$this->encrypt(json_encode($params,JSON_UNESCAPED_UNICODE));
        $api_params=[
            'timestamp'=>time().'000',
            'reqId'=>create_order(),
            'data'=>$res,
            'channelCode'=>$this->channelCode
        ];


        $res_json = $this->postJson($api_url, $api_params);
        $res  = json_decode($res_json, true);
//        dump($params);
//        dump($api_params);
//        dump($res);
//        die;
        if(!empty($res)){
            if($res['code']!=0){
                $res['params']=$params;
                $errMsg=$apiName.'CRM手机号码的撞库失败：'.$res['msg'];
                ClueErrorLog::record($clue_info['clue_id'],$errMsg,$res);
                model('Clue')->where('id',$clue_info['id'])->update(['err_msg'=>$errMsg]);
                throw new ParamException(['msg'=>$errMsg,'errorCode'=>10001]);
            }else{
//                if($res['data']['phoneMd5Exist']){
//                    if(empty($clue_info['is_find'])&&!empty($clue_info['clue_city']) && $clue_info['clue_city'] != $clue_info['city']){
//                        $clue_info['city'] = $clue_info['clue_city'];
//                        $clue_info['next_city'] = $clue_info['clue_city'];
//                        $listPush[]=$clue_info['push_id'];
//                        $clueRes=(new ClueModel())->cluePush($clue_info, false, $listPush);
//                        if($clueRes['code']!=200){
//                            $errMsg=$clueRes['msg'];
//                            ClueErrorLog::record($clue_info['clue_id'],$errMsg,$res);
//                            model('Clue')->where('id',$clue_info['id'])->update(['err_msg'=>$errMsg]);
//                            throw new ParamException(['msg'=>$errMsg,'errorCode'=>10001]);
//                        }
//                    }else{
//                        $errMsg=$apiName.'CRM手机号码的撞库重复';
//                        ClueErrorLog::record($clue_info['clue_id'],$errMsg,$res);
//                        model('Clue')->where('id',$clue_info['id'])->update(['err_msg'=>$errMsg]);
//                        $isRe=Db::name('clue_err_log')->where(['type'=>2,'adv_id'=>$clue_info['adv_id'],'pro_id'=>$clue_info['pro_id'],'clue_id'=>$clue_info['id']])->find();
//                        if(empty($isRe)){
//                            Db::name('clue_err_log')->insert([
//                                'type'=>2,
//                                'clue_id'=>$clue_info['id'],
//                                'adv_id'=>$clue_info['adv_id'],
//                                'pro_id'=>$clue_info['pro_id'],
//                                'city'=>$clue_info['city'],
//                                'create_time'=>time()]);
//                        }
//                        if(empty($clue_info['is_find'])){
//                            $listPush[]=$clue_info['push_id'];
//                            $clueRes=(new ClueModel())->cluePush($clue_info, false, $listPush);
//                            if($clueRes['code']!=200){
//                                $errMsg=$clueRes['msg'];
//                                ClueErrorLog::record($clue_info['clue_id'],$errMsg,$res);
//                                model('Clue')->where('id',$clue_info['id'])->update(['err_msg'=>$errMsg]);
//                                throw new ParamException(['msg'=>$errMsg,'errorCode'=>10001]);
//                            }
//                        }else{
//                            throw new ParamException(['msg'=>$errMsg,'errorCode'=>10001]);
//                        }
//                    }
//                }
            }
        }else{
            $errMsg=$apiName.'CRM手机号码的撞库请求失败';
            ClueErrorLog::record($clue_info['clue_id'],$errMsg,$clue_info);
            model('Clue')->where('id',$clue_info['id'])->update(['err_msg'=>$errMsg]);
            throw new ParamException(['msg'=>$errMsg,'errorCode'=>10001]);
        }
        return $res;
    }

    /**
     * post发送json格式的数据
     */
    public function postJson($url, $data)
    {
        $curl = curl_init();

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_TIMEOUT, 10);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        if (!$data) {
            throw new ParamException(['msg' => '请求数据不能为空', 'errorCode' => 10000]);
        }
        $params = json_encode($data, JSON_UNESCAPED_UNICODE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json; charset=utf-8',
        ));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $res = curl_exec($curl);
        curl_close($curl);
        //writelog("请求日志".$params. "====". $res. "====". $url);
        return $res;
    }

    public function postData($url, $data)
    {
        $curl = curl_init();

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_TIMEOUT, 10);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        if (!$data) {
            throw new ParamException(['msg' => '请求数据不能为空', 'errorCode' => 10000]);
        }
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_HEADER, 0);
//        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
//            'Content-Type: application/json; charset=utf-8',
//        ));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $res = curl_exec($curl);
        curl_close($curl);
        //writelog("请求日志".$params. "====". $res. "====". $url);
        return $res;
    }



}